package com.shuai.jit.security.service;

import com.shuai.jit.entity.user.Permission;
import com.shuai.jit.entity.user.User;
import com.shuai.jit.mapper.PermissionMapper;
import com.shuai.jit.mapper.UserMapper;
import com.shuai.jit.security.entity.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用来登录的的设置
 */
@Service("jwtUserDetailsService")
@Slf4j
public class JwtUserDetailsService  implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取到数据库 的用户名 和用户密码--为前端 password+salt
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查找数据库
        User user= userMapper.selectByName(username);
        if(user==null){
            throw  new UsernameNotFoundException("对不起，用户名找不到");
        }
        // 把密码放入redis 中
        redisTemplate.opsForValue().set(user.getPassword(),user.getSalt());
        List<String> authorityList = new ArrayList<>();

        // 这里读取权限表，然后查看
        // 根据用户的等级，获取全部的权限
        List<Permission> permissions=permissionMapper.selectByLev(user.getUserLev());
        // 添加路径
        for (Permission p:permissions){
            authorityList.add(p.getPath());
        }
        return new SecurityUser(user,authorityList);
    }

}